package com.health.mapp.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

 


import com.health.mapp.service.Upload;
import com.health.mapp.utils.PropertiesUtil;
import com.health.commons.PropertiesService;

public class Upload extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4451502459409874160L;
	private static Logger logger = Logger.getLogger(Upload.class);
    static Map<String,String> OSMap= new HashMap<String,String>();
    static Map<String,String> pathMap= new HashMap<String,String>();
	/**
	 * Constructor of the object.
	 */
	public Upload() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("");
		out.flush();
		out.close();
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int bodyLen = request.getContentLength();
		logger.debug("Upload file ContentLength = " + bodyLen);
		String result = null;
		try {

			String disposition = request.getHeader("Content-Disposition");
			String prefix = null;
			logger.debug("request header Content-Disposition :" + disposition);
			if (null != disposition && 0 <= disposition.indexOf("filename=")) {
				String substr = disposition.substring(disposition.indexOf("filename=\"") + 10);
				String fileName = null;
				if (0 <= substr.indexOf("\"")) {
					fileName = substr.substring(0, substr.indexOf("\""));
				} else {
					fileName = substr;
				}
				 
				prefix = getExtensionName(fileName);
			} else {
				prefix = "jpg";
			}
			logger.debug("Content type is " + prefix);
			String tempPath = PropertiesService.getString("upload.temp.path");
			 
			logger.debug("os.name:" + OSMap.get("os.name"));
			
			ServletContext sc = this.getServletContext();
 
			String rootPath = sc.getRealPath("/");
			
			
			if (OSMap.get("os.name").toString().contains("Windows")) {

 
				tempPath = pathMap.get("windows.upload.temp.path");
			 
			} else if (OSMap.get("os.name").toString().contains("Linux")) { 
				 
			 

				tempPath =pathMap.get("unix.upload.temp.path");
			}
			String destPath=rootPath+tempPath;
			
			
			logger.debug("destPath is " + destPath);
			File tempFp = new File(destPath);
			// 创建目录
			if (!tempFp.exists()) {
				tempFp.mkdirs();// 目录不存在的情况下，创建目录
			}

			String sessionid = request.getSession().getId() + "." + prefix;
			String tmpfileName = destPath + File.separator + sessionid;
			logger.debug("Upload file name :" + tmpfileName);
			FileOutputStream tmpfileStream = null;
			try {
				tmpfileStream = new FileOutputStream(tmpfileName);// 创建tmpfileName的文件中写入文件流
				int post = 0;
				byte[] cache = new byte[4096];
				while (post < bodyLen) {
					int len = request.getInputStream().read(cache);
					if (len <= 0) {
						logger.error("READ SOCKET ERROR!");
						break;
					}
					tmpfileStream.write(cache, 0, len);
					post += len;
				}

				result = String.format("{\"errorCode\":0, \"id\":\"%s\"}", sessionid);
				logger.debug(String.format("Upload file[%s] success.[size=%d]", tmpfileName, post));
			} catch (Exception e) {
				result = String.format("{\"errorCode\":300009}");
				logger.debug(String.format("Upload file[%s] fail.", tmpfileName));
				e.printStackTrace();
			} finally {
				if (null != tmpfileStream) {
					try {
						tmpfileStream.close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			result = String.format("{\"errorCode\":300009}");
			e.printStackTrace();
		}
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(result);
		out.flush();
		out.close();
	}

	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		
			logger.debug("upload init...");
		     getOSInfo();
		      String   file_real_path=this.getServletContext().getRealPath("/");  
		      
		      if (OSMap.get("os.name").toString().contains("Windows"))
				{

		    	  pathMap= PropertiesUtil.createConfig_Upload_Map();
					 
					 
										
				}
				else if (OSMap.get("os.name").toString().contains("Linux") || OSMap.get("os.name").toString().contains("linux")|| OSMap.get("os.name").toString().contains("Unix")||OSMap.get("os.name").toString().contains("unix")) 
				{
							
					  pathMap= PropertiesUtil.createConfig_Upload_Map();
				 
				}
		      
	    	  
	}

	/**
	 * 获取系统属性集
	 *  
	 * @return
	 */
	public void getOSInfo()
	{
		
		
		
		 Properties props=System.getProperties(); //获得系统属性集
		 
		 
		 //操作系统名称   
		 OSMap.put("os.name", props.getProperty("os.name"));
		 //操作系统构架   
		 OSMap.put("os.arch", props.getProperty("os.arch"));
		 //操作系统版本  
		 OSMap.put("os.version", props.getProperty("os.version"));
		 //Java 运行时环境版本 
		 OSMap.put("java.version", props.getProperty("java.version"));
		  
		// java.vendor Java 运行时环境供应商
		 OSMap.put("java.vendor", props.getProperty("java.vendor"));
		 // Java 供应商的 URL 
		 OSMap.put("java.vendor.url", props.getProperty("java.vendor.url"));
		//  Java 安装目录 
		 OSMap.put("java.home", props.getProperty("java.home"));
		  //Java 虚拟机规范版本 
		 OSMap.put("java.vm.specification.version", props.getProperty("java.vm.specification.version"));
		//  Java 虚拟机规范供应商 
		 OSMap.put("java.vm.specification.vendor", props.getProperty("java.vm.specification.vendor"));
		 // Java 虚拟机规范名称 
		 OSMap.put("java.vm.specification.name", props.getProperty("java.vm.specification.name"));
		  //Java 虚拟机实现版本 
		 OSMap.put("java.vm.version", props.getProperty("java.vm.version"));
		  //Java 虚拟机实现供应商 
		 OSMap.put("java.vm.vendor", props.getProperty("java.vm.vendor"));
		 // Java 虚拟机实现名称 
		 OSMap.put("java.vm.name", props.getProperty("java.vm.name"));
		  //Java 运行时环境规范版本 
		 OSMap.put("java.specification.version", props.getProperty("java.specification.version"));
		  //Java 运行时环境规范供应商 
		 OSMap.put("java.specification.vendor", props.getProperty("java.specification.vendor"));
		  //Java 运行时环境规范名称 
		 OSMap.put("java.specification.name", props.getProperty("java.specification.name"));
		 // Java 类格式版本号 
		 OSMap.put("java.class.version", props.getProperty("java.class.version"));
		  //Java 类路径 
		 OSMap.put("java.class.path", props.getProperty("java.class.path"));
		//  加载库时搜索的路径列表
		 OSMap.put("java.library.path", props.getProperty("java.library.path"));
		 // 默认的临时文件路径 
		 OSMap.put("java.io.tmpdir", props.getProperty("java.io.tmpdir"));
		  //要使用的 JIT 编译器的名称 
		 OSMap.put("java.compiler", props.getProperty("java.compiler"));
		 
		 //一个或多个扩展目录的路径 
		 OSMap.put("java.ext.dirs", props.getProperty("java.ext.dirs"));
	 
		 
		 //文件分隔符（在 UNIX 系统中是“/”） 
		 OSMap.put("jfile.separator ", props.getProperty("file.separator "));
		 
		 //路径分隔符（在 UNIX 系统中是“:”） 
		 OSMap.put("path.separator", props.getProperty("path.separator"));
		 
		 //行分隔符（在 UNIX 系统中是“/n”） 
		 OSMap.put("line.separator ", props.getProperty("line.separator "));
		 
		 //用户的账户名称 
		 OSMap.put("user.name ", props.getProperty("user.name "));
		 // 用户的主目录 
		 OSMap.put("user.home", props.getProperty("user.home"));
		//  用户的当前工作目录 
		 OSMap.put("user.dir", props.getProperty("user.dir"));

 
		
	}
	
	
}
